<template>
  <div>
    <a-card :bordered="false">
      <div class="table-page-search-wrapper">
        <a-form layout="inline">
          <a-row :gutter="48">
            <a-col :md="10" :sm="24">
              <a-form-item label="排放时间">
                <a-range-picker
                  :show-time="{ format: 'HH:mm' }"
                  format="YYYY-MM-DD HH:mm"
                  :placeholder="['开始时间', '结束时间']"
                />
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="船名">
                <a-input v-model="queryParam.id" placeholder="" />
              </a-form-item>
            </a-col>
            <a-col :md="(!advanced && 6) || 24" :sm="24">
              <span
                class="table-page-search-submitButtons"
                :style="(advanced && { float: 'right', overflow: 'hidden' }) || {}"
              >
                <a-button type="primary" @click="$refs.table.refresh(true)">查询</a-button>
                <a-button style="margin-left: 8px" @click="() => (this.queryParam = {})">重置</a-button>
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>

      <div class="table-operator">
        <a-button type="primary" icon="plus" @click="handleAdd">新建</a-button>
      </div>

      <!-- <step-by-step-modal ref="modal" @ok="handleOk" /> -->
    </a-card>
    <a-card :bordered="false">
      <a-card-grid style="width: 50%; text-align: center">
        <s-table
          ref="table"
          size="default"
          :rowKey="setRowKey"
          :customRow="onClickRow"
          :rowClassName="setRowClassName"
          :columns="columns"
          :data="loadData"
          showPagination="auto"
          class="components-table-demo-nested"
          @expand="open"
          :expandedRowKeys="expandedRowKeys"
        >
          <s-table
            :rowKey="setRowDetailKey"
            slot="expandedRowRender"
            :columns="innerColumns"
            :data="loadDataDetail"
            :customRow="onClickDRow"
            :rowClassName="setDRowClassName"
            :showPagination="false"
          >
            <span slot="action" slot-scope="text, record">
              <template>
                <a @click="handleAuth(record)">审核</a>
              </template>
            </span>
          </s-table>
          <!-- <span slot="serial" slot-scope="text, record, index">
            {{ index + 1 }}
          </span> -->
          <span slot="action" slot-scope="text, record" class="table-operation">
            <template>
              <a @click="handleEdit(record)">修改</a>
              <a-divider type="vertical" />
              <a class="delete" @click="handleDel(record)">删除</a>
            </template>
          </span>
        </s-table>
      </a-card-grid>
      <a-card-grid style="width: 50%; text-align: center">
        <create-form
          ref="createModal"
          :loading="confirmLoading"
          :model="mdl"
          @cancel="handleCancel"
          @ok="handleOk"
          @reject="handleReject"
          @pass="handlePass"
        />
      </a-card-grid>
    </a-card>
    <a-modal
      title="删除"
      :visible="delvisible"
      :confirm-loading="confirmLoading"
      okType="danger"
      @ok="delOk"
      @cancel="delCancel"
    >
      <p>确认删除该数据?</p>
    </a-modal>
  </div>
</template>

<script>
import moment from 'moment'
import { STable, Ellipsis } from '@/components'
import { GetList, Delete, Add, Edit, AuthSuc, AuthFail } from '@/api/fivejointsingle'
import CreateForm from './modules/Form'

const columns = [
  // {
  //   title: '#',
  //   scopedSlots: { customRender: 'serial' },
  // },
  {
    title: '编号',
    dataIndex: 'docId',
  },
  {
    title: '排放地点',
    dataIndex: 'dischargePlace',
  },
  {
    title: '排放时间',
    dataIndex: 'dischargeTimeStr',
  },
  {
    title: '联系方式',
    dataIndex: 'managerContact',
  },
  {
    title: '负责人',
    dataIndex: 'managerName',
  },
  {
    title: '船舶编号',
    dataIndex: 'vesselMmsi',
  },
  {
    title: '关联船舶',
    dataIndex: 'vesselName',
  },
  {
    title: '操作',
    dataIndex: 'action',
    // fixed: 'right',
    width: 120,
    scopedSlots: { customRender: 'action' },
  },
]
const innerColumns = [
  { title: '污染物种类', dataIndex: 'pollutantType', key: 'pollutantType' },
  { title: '污染物种类', dataIndex: 'pollutantSort', key: 'pollutantSort' },
  { title: '接收单位', dataIndex: 'processState', key: 'processState' },
  { title: '体积/重量', dataIndex: 'pollutantVolume', key: 'pollutantVolume' },
  { title: '处理情况', dataIndex: 'returnFlag', key: 'returnFlag' },
  {
    title: '处理说明',
    dataIndex: 'remark',
    key: 'remark',
  },
  {
    title: '操作',
    dataIndex: 'action',
    // fixed: 'right',
    width: 120,
    scopedSlots: { customRender: 'action' },
  },
]

export default {
  name: 'TableList',
  components: {
    STable,
    Ellipsis,
    CreateForm,
  },
  data() {
    this.columns = columns
    this.innerColumns = innerColumns
    return {
      // create model
      visible: false,
      delvisible: false,
      confirmLoading: false,
      mdl: null,
      // 高级搜索 展开/关闭
      advanced: false,
      delid: 0,
      list: {},
      detail: [],
      // 查询参数
      queryParam: {},
      // 加载数据方法 必须为 Promise 对象
      loadData: (parameter) => {
        const requestParameters = Object.assign(
          { pageIndex: parameter.pageNo, pageSize: parameter.pageSize },
          this.queryParam
        )
        console.log('loadData request parameters:', requestParameters)
        return GetList(requestParameters).then((res) => {
          const data = {
            data: [],
            pageNo: res.data.pageIndex,
            pageSize: res.data.pageSize,
            totalCount: res.data.total,
            totalPage: res.data.pageLimit,
          }
          res.data.list.forEach((value) => {
            const da = { ...value.main, detail: value.details }
            data.data.push(da)
          })
          // res.data.forEach((value) => {
          //   const da = { ...value.main, detail: value.details }
          //   data.data.push(da)
          // })
          this.list = data.data
          this.detail=[]
          this.loadDataDetail()
          this.expandedRowKeys = []
          return data
        })
      },
      loadDataDetail: () => {
        return new Promise((resolve, reject) => {
          setTimeout(() => {
            resolve()
          }, 1000)
        }).then((res) => {
          const data = {
            data: this.detail,
          }
          debugger
          return data
        })
      },
      rowId: 0,
      drowId: 0,
      expandedRowKeys: [],
      innerData: [],
      POLLUTANT_TYPE: [],
    }
  },
  filters: {},
  created() {
    // const that = this
    // that.$store.dispatch('GetPOLLUTANT_TYPE').then(() => {
    //   that.POLLUTANT_TYPE = that.$store.getters.POLLUTANT_TYPE
    // })
    // getRoleList({ t: new Date() })
  },
  computed: {},
  methods: {
    onClickRow(record) {
      return {
        on: {
          click: () => {
            this.rowId = record.docId
          },
          dblclick: () => {
            this.visible = true
            this.mdl = { ...record }
          },
        },
      }
    },
    onClickDRow(record) {
      return {
        on: {
          click: () => {
            this.drowId = record.detailId
            this.rowId = record.docId
          },
        },
      }
    },
    setRowClassName(record) {
      return record.docId === this.rowId ? 'ant-table-row-selected2' : ''
    },
    setDRowClassName(record) {
      return record.detailId === this.drowId ? 'ant-table-row-selected2' : ''
    },
    setRowKey(record) {
      return record.docId
    },
    setRowDetailKey(record) {
      return 'deatail' + record.detailId
    },
    handleAdd() {
      this.mdl = null
      this.visible = true
    },
    handleEdit(record) {
      this.visible = true
      this.mdl = { ...record }
    },
    handleAuth(record) {
      const main = this.list.find((m) => m.docId == record.docId)
      const data = {
        ...main,
      }
      data.detail = []
      data.detail.push(record)
      this.visible = true
      this.mdl = { ...data, auth: 'auth' }
    },
    handleDel(record) {
      this.delid = record.docId
      this.delvisible = true
    },
    delOk(e) {
      this.confirmLoading = true
      Delete(this.delid).then((res) => {
        this.$message.info('删除成功')
        this.$refs.table.refresh()
      })
      this.delvisible = false
      this.confirmLoading = false
    },
    delCancel(e) {
      this.delvisible = false
    },
    handleOk() {
      const cmdel = this.$refs.createModal
      const form = this.$refs.createModal.form
      this.confirmLoading = true
      form.validateFields((errors, values) => {
        if (!errors) {
          console.log('values', values)
          const data = {
            main: {},
            details: [],
          }
          data.main = {
            vesselName: values.vesselName,
            dischargeTimeStr: moment(values.dischargeTimeStr).format('YYYY-MM-DD HH:mm'),
            dischargePlace: values.dischargePlace,
            vesselMmsi: values.vesselMmsi,
            managerName: values.managerName,
            managerContact: values.managerContact,
            remark: values.remark,
          }
          cmdel.detailList.forEach((value) => {
            const da = {
              pollutantSort: value.pollutantSort,
              pollutantType: value.pollutantType,
              pollutantWeight: value.pollutantWeight,
              pollutantVolume: value.pollutantVolume,
            }
            data.details.push(da)
          })
          if (values.docId > 0) {
            data.docId = values.docId
            // 修改 e.g.
            Edit(data).then((res) => {
              this.visible = false
              this.confirmLoading = false
              // 重置表单数据
              form.resetFields()
              this.$refs.createModal.detailList = []
              // 刷新表格
              this.$refs.table.refresh()

              this.$message.info('修改成功')
            })
          } else {
            // 新增
            Add(data).then((res) => {
              this.visible = false
              this.confirmLoading = false
              // 重置表单数据
              form.resetFields()
              this.$refs.createModal.detailList = []
              // 刷新表格
              this.$refs.table.refresh()

              this.$message.info('新增成功')
            })
          }
        } else {
          this.confirmLoading = false
        }
      })
    },
    handlePass() {
      const cmdel = this.$refs.createModal
      const form = this.$refs.createModal.form
      this.confirmLoading = true
      form.validateFields((errors, values) => {
        if (!errors) {
          console.log('values', values)
          const data = {
            processState: cmdel.detailList[0].processState,
            unitId: values.unitId,
            unitName: values.unitName,
            opinion: values.opinion,
            detailId: cmdel.detailList[0].detailId,
          }
          AuthSuc(data).then((res) => {
            this.visible = false
            this.confirmLoading = false
            // 重置表单数据
            form.resetFields()
            this.$refs.createModal.detailList = []
            // 刷新表格
            this.$refs.table.refresh()
            this.$message.info('审核成功')
          })
        } else {
          this.confirmLoading = false
        }
      })
    },
    handleReject() {
      const cmdel = this.$refs.createModal
      const form = this.$refs.createModal.form
      this.confirmLoading = true
      form.validateFields((errors, values) => {
        if (!errors) {
          console.log('values', values)
          const data = {
            returnFlag: 'Y',
            processState: cmdel.detailList[0].processState,
            unitId: values.unitId,
            unitName: values.unitName,
            opinion: values.opinion,
            detailId: cmdel.detailList[0].detailId,
          }
          AuthFail(data).then((res) => {
            this.visible = false
            this.confirmLoading = false
            // 重置表单数据
            form.resetFields()
            this.$refs.createModal.detailList = []
            // 刷新表格
            this.$refs.table.refresh()
            this.$message.info('退回成功')
          })
        } else {
          this.confirmLoading = false
        }
      })
    },
    handleCancel() {
      this.visible = false

      const form = this.$refs.createModal.form
      form.resetFields() // 清理表单数据（可不做）
    },
    toggleAdvanced() {
      this.advanced = !this.advanced
    },
    resetSearchForm() {
      this.queryParam = {
        date: moment(new Date()),
      }
    },
    open(expanded, record) {
      if (expanded) {
        const params = {
          id: record.docId,
        }
        this.detail = this.list.find((m) => m.docId == record.docId).detail
        // this.loadDataDetail(detail)
        this.expandedRowKeys = []
        this.expandedRowKeys.push(record.docId)
      } else {
        this.expandedRowKeys = []
      }
    },
  },
}
</script>
